package com.study.newjava8.forkjoin;

import org.junit.Test;
import org.omg.PortableServer.POA;

import javax.sound.midi.Soundbank;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class TestForkJoin {
    /**
     * 使用ForkJoin完成0到1亿累加
     */
    @Test
    public void test1(){
        ForkJoinPool pool=new ForkJoinPool();
        Instant start = Instant.now();
        ForkJoinTask<Long> task= new ForkJoinText(0,10000000000L);
        Long sum = pool.invoke(task);
        Instant end =Instant.now();
        System.out.println(sum);
        System.out.println(Duration.between(start,end).toMillis());

    }


    @Test
    public void test2(){
        Instant start = Instant.now();
        long sum=0L;
        for (long i = 0; i <= 10000000000L; i++) {
            sum+=i;
        }
        Instant end =Instant.now();
        System.out.println(sum);
        System.out.println(Duration.between(start,end).toMillis());
    }
    /**
     * java并行流
     */
    @Test
    public void test3(){

        Instant start = Instant.now();
        //切换成并行流
        long sum = LongStream.rangeClosed(0, 100000000L)
                .parallel()
                .reduce(0, Long::sum);
        Instant end =Instant.now();
        System.out.println(sum);
        System.out.println(Duration.between(start,end).toMillis());

    }
}
